package com.cz.nongyetongv5.utils;

import android.content.Context;
import android.util.Log;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.adapter.config.CommonConstants;
import com.cz.nongyetongv5.adapter.dao.DatabaseHelper;
import com.cz.nongyetongv5.bean.BeiJianDanWei;
import com.cz.nongyetongv5.bean.ChouYanJiGou;
import com.cz.nongyetongv5.bean.Delbean;
import com.cz.nongyetongv5.bean.HttpBack;
import com.cz.nongyetongv5.bean.JianChaDanWei;
import com.cz.nongyetongv5.bean.JianChaRenYuan;
import com.cz.nongyetongv5.bean.LinkMan;
import com.cz.nongyetongv5.bean.User;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UpdateDateUtilEx extends UpdateDataUtil{


	private String PlanCheckUrl="";
	public UpdateDateUtilEx(DatabaseHelper db, Context context, User user) {
		super(db, context, user);
		PlanCheckUrl=context.getResources().getString(R.string.upload_plancheck);
	}

	public int sumAdd(String tableName,int start,String maxTime,String regcode,String opt){

		String url = new ConfigUtil(context.getResources()).getPreHttpUrl();
		if(tableName.equals("CHOUYANJIGOU")){
			url+= context.getString(R.string.update_jiancejigouInfo);
		}
		if(tableName.equals("JIANCHADANWEI")){
			url+= context.getString(R.string.update_jianchadanweiInfo);
		}
		if(tableName.equals("JIANGUANRENYUAN")){
			url+= context.getString(R.string.update_jiancharenyuan);
		}
		if(tableName.equals("LINKMAN")){
			url+= context.getString(R.string.update_lianxiren);
		}

		url+= opt+"/region_code/" +regcode + "/time/"
				+ maxTime + "/limit/"+(start+20)+"/offset/"+start+"/username/" + user.getUsername()
				+ "/from/1";
		Log.d("rafe url",url);
		HttpUtilsEx HttpUtilsEx = new HttpUtilsEx();

		HttpBack data= HttpUtilsEx.sendRequest2(url,null, "GET", "UTF-8", authUserName,
				authPassword, user);
		if (data.getCode()!=200||!CharsetUtil.isNotNull(data.getData())) {
			return -500;
		}
		JSONObject jsonObj =null;
		try {
			jsonObj = new JSONObject(data.getData());
		} catch (JSONException e) {
			e.printStackTrace();
			return -500;
		}

		String status = jsonObj.optString("status");

		if (CommonConstants.serverIsOk(status)) {

			JSONArray jsonArray = jsonObj
					.optJSONArray("result");
			if(tableName.equals("JIANGUANRENYUAN")){
				List<JianChaRenYuan> jianChaDanWeis = new ArrayList<JianChaRenYuan>();
				String addTime = jsonObj.optJSONObject(
						"modified").optString("datetime");
				for (int i = 0; i < jsonArray.length(); i++) {

					JSONObject jsonObjItem = jsonArray
							.optJSONObject(i);

					if (!jsonObjItem.isNull("id")) {

						String id = jsonObjItem.optString("id");

						String name = "";

						if (!jsonObjItem.isNull("realname")) {
							name = jsonObjItem
									.optString("realname");
						}

						Integer rank = jsonObjItem
								.optInt("rank");

						String code = jsonObjItem
								.optLong("region_code") + "";

						JianChaRenYuan jianChaDanWei = new JianChaRenYuan(
								id, name, rank, code, addTime,
								null, null);

						jianChaDanWeis.add(jianChaDanWei);
					}

				}

				db.insertOrUpdateJianChaRenYuan(jianChaDanWeis);
				return jsonObj.optInt("total");
			}
			if(tableName.equals("LINKMAN")){


				List<LinkMan> linkMans = new ArrayList<LinkMan>();

				String addTime = jsonObj.optJSONObject(
						"modified").optString("datetime");

				for (int i = 0; i < jsonArray.length(); i++) {

					JSONObject linkManObjJson = jsonArray
							.optJSONObject(i);

					String id = linkManObjJson.optString("id");

					String realName = linkManObjJson
							.optString("realname");

					Integer sex = linkManObjJson.optInt("sex");

					String tel = linkManObjJson
							.optString("tel");

					String mobile = linkManObjJson
							.optString("mobile");

					String departmentName = linkManObjJson
							.optString("department_name");

					String post = linkManObjJson
							.optString("post");

					Integer rank = linkManObjJson
							.optInt("rank");

					Double longitude = linkManObjJson
							.isNull("longitude") ? null
							: linkManObjJson
							.optDouble("longitude");

					Double latitude = linkManObjJson
							.isNull("latitude") ? null
							: linkManObjJson
							.optDouble("latitude");

					String regionCode = linkManObjJson
							.optLong("region_code") + "";

					LinkMan linkMain = new LinkMan(id,
							realName, sex, tel, mobile,
							departmentName, post, rank,
							longitude, latitude, regionCode,
							addTime, null, null);

					linkMans.add(linkMain);

				}
				db.insertOrUpdateLinkMan(linkMans);
				return jsonObj.optInt("total");
			}
			if(tableName.equals("CHOUYANJIGOU")){
				List<ChouYanJiGou> chouYanJiGous = new ArrayList<ChouYanJiGou>();

				String addTime = jsonObj.optJSONObject(
						"modified").optString("datetime");

				for (int i = 0; i < jsonArray.length(); i++) {

					JSONObject jsonObjItem = jsonArray
							.optJSONObject(i);

					String id = jsonObjItem.optString("id");

					String name = jsonObjItem.optString("name");

					String code = jsonObjItem
							.optLong("region_code") + "";

					String tel = null;

					if (!jsonObjItem.isNull("tel")) {
						tel = jsonObjItem.optString("tel");
					}

					ChouYanJiGou chouYanJiGou = new ChouYanJiGou(
							id, name, code, addTime, null,
							null, tel);

					chouYanJiGous.add(chouYanJiGou);

				}
				db.insertOrUpdateChouYangJiGou(chouYanJiGous);
				return jsonObj.optInt("total");



			}

			if(tableName.equals("JIANCHADANWEI")){
				List<JianChaDanWei> jianChaDanWeis = new ArrayList<JianChaDanWei>();
				String addTime = jsonObj.optJSONObject(
						"modified").optString("datetime");

				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject bjdwJsonObj = jsonArray
							.optJSONObject(i);

					if (!bjdwJsonObj.isNull("id")) {

						String id = bjdwJsonObj.optString("id");

						String name = bjdwJsonObj
								.optString("name");

						String code = bjdwJsonObj
								.optLong("region_code") + "";

						JianChaDanWei jianChaDanWei = new JianChaDanWei(
								id, name, code, addTime, null,
								null);

						jianChaDanWeis.add(jianChaDanWei);
					}

				}
				db.insertOrUpdateJianChaDanWei(jianChaDanWeis);
				return jsonObj.optInt("total");
			}
		}

		return -1;

	}

	public JSONObject getPlanObject(String planid,int start,String maxTime,String opt){

		String datastr="<?xml version=\"1.0\" encoding=\"utf-8\"?>"
				+"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\">"
				+"<soap:Body>"
				+"<getMonitorPlan xmlns=\"http://tempuri.org/\">"
				+"<szUser>"+user.getUsername()+"</szUser>"
				+"<szRegion>"+user.getKnowRegion()+"</szRegion>"
				+"<nPlanID>"+planid+"</nPlanID>"
				+"<szType>"+opt+"</szType>"
				+"<dtTime>"+maxTime+"</dtTime>"
				+"<nOffset>"+start+"</nOffset>"
				+"<nSize>10</nSize>"
				+"</getMonitorPlan>"
				+"</soap:Body>"
				+"</soap:Envelope>";
		Log.d("rafe_checkplan_"+maxTime, datastr);

		HttpUtilsEx HttpUtilsEx = new HttpUtilsEx();
		HttpBack data=HttpUtilsEx.sendRequest3(PlanCheckUrl,datastr);
		JSONObject plans=new JSONObject();
		Log.d("rafe_checkplan_"+maxTime,String.valueOf(data.getData()));
		if(data.getData()==null)return null;
		String[] d1=data.getData().split("<getMonitorPlanResult>");
		if(d1.length>1){
			d1=d1[1].split("</getMonitorPlanResult>");
			try {
				plans=new JSONObject(d1[0]);
			} catch (JSONException e) {
				e.printStackTrace();
				return null;
			}
		}
		return plans;

	}
	public int sumPlan(int start,String maxTime,String opt){
		JSONObject plans=getPlanObject("0",start,maxTime,opt);
		if(plans==null)return -2;
		JSONArray ps=plans.optJSONArray("data");
		Log.d("rafe_plan_Datas",String.valueOf(ps));
		if(ps==null)return -1;
		for(int i=0;i<ps.length();i++){
			JSONObject plan=ps.optJSONObject(i);
			if(plan.optInt("appoint_ent",0)>0){
				int entstart=0;
				String pid=plan.optString("id","0");
				int entsum=sumPlanEnts(pid,entstart,maxTime);
				if(entsum>0){
					while(entstart<entsum){
						entstart+=10;
						Log.d("rafe plan ent", "pre start:"+entstart+"?planid="+pid);
						if(sumPlanEnts(pid,start,maxTime)<0){
							Log.d("rafe plan ent", "婵炲备鍓濆﹢涔竘anel");
							break;
						}
					}
					Log.d("rafe plan ent", "complete");
				}
			}
		}
		if(ps.length()>0){
			if(opt.equals("delete")){
				db.deletePlan(ps);
			}else
				db.insertOrUpdateMoinitorPlan(ps,opt);
		}
		return plans.optInt("totalCount",-1);

	}

	public int sumPlanEnts(String planid,int start,String maxTime){
		JSONObject plans=getPlanObject(planid,start,maxTime,"add");
		if(plans==null)return -2;
		JSONArray ps=plans.optJSONArray("data");
		if(ps==null)return -1;
		else{
			db.insertOrUpdateMoinitorPlanEnts(ps);
		}
		return plans.optInt("totalCount",-1);
	}
	public int updateTown(int start) {


		String url = new ConfigUtil(context.getResources()).getPreHttpUrl()
				+ "rest/region/newmlists/limit/1000/offset/"+start+"/username/"
				+ user.getUsername() + "/from/1";

		Log.d("rafe  URL  new town",url);

		HttpUtilsEx HttpUtilsEx = new HttpUtilsEx();
		HttpBack data=HttpUtilsEx.sendRequest2(url, null, "GET", "UTF-8", authUserName,
				authPassword, user);

		if(data!=null&&data.getCode()==200){
			if (CharsetUtil.isNotNull(data.getData())) {
				try {
					JSONObject jsonObj = new JSONObject(data.getData());
					if (jsonObj.optString("status","false").equals("true")) {
						JSONArray jsonArray = jsonObj
								.getJSONArray("result");

						if(jsonArray.length()>0){
							db.updateReginCount0421(jsonArray);
						}

						return  jsonArray.length();
					}else{
						return -200;
					}

				} catch (JSONException e) {
					return -500;
				}

			}else{
				return -500;
			}



		}else{
			Log.d("rafe error500",String.valueOf(data.getData()));
			return -500;
		}
	}
	public Delbean sumDelect(String tableName,int start,String maxTime,String code) {
		Delbean back=new Delbean();
		String urlTabName = "";
		if ("BEIJ".equals(tableName.substring(0, 4))) {
			urlTabName = "ent";

		} else if ("JIANCHADANWEI".equals(tableName)) {
			urlTabName = "department";
		} else if ("JIANGUANRENYUAN".equals(tableName)) {
			urlTabName = "team";
		} else if ("LINKMAN".equals(tableName)) {
			urlTabName = "contact";
		} else if ("CHOUYANJIGOU".equals(tableName)) {
			urlTabName = "detector";
		}

		String url = new ConfigUtil(context.getResources()).getPreHttpUrl()
				+ "rest/recorder/index/table/" + urlTabName
				+ "/type/delete/time/" + maxTime + "/limit/20/offset/"+start+"/username/"
				+ user.getUsername() + "/from/1";
		if ("BEIJ".equals(tableName.substring(0, 4))) {
			url+="/region_code/"+code;
		}
		Log.d("rafe  URL DEL",url);

		HttpUtilsEx HttpUtilsEx = new HttpUtilsEx();
		HttpBack data=HttpUtilsEx.sendRequest2(url, null, "GET", "UTF-8", authUserName,
				authPassword, user);
		if(data.getCode()==200){
			if (CharsetUtil.isNotNull(data.getData())) {

				try {
					JSONObject jsonObj = new JSONObject(data.getData());
					String status = jsonObj.optString("status");
					if (CommonConstants.serverIsOk(status)) {

						String deleteTime = jsonObj.optJSONObject(
								"modified").optString("datetime");

						JSONArray jsonArray = jsonObj
								.getJSONArray("result");

						List<String> ids = new ArrayList<String>();

						for (int i = 0; i < jsonArray.length(); i++) {

							JSONObject bjdwJsonObj = jsonArray
									.optJSONObject(i);

							if (!bjdwJsonObj.isNull("id")) {
								Log.d("rafe dele",String.valueOf(bjdwJsonObj));
								String id = bjdwJsonObj.optString("id");
								ids.add(id);
							}

						}

						Map<String, String> times = new HashMap<String, String>();

						times.put("ADDTIME", db.queryMaxMotifyTime(
								tableName, "ADDTIME", user.getKnowRegion()));

						times.put("MODIFYTIME", db.queryMaxMotifyTime(
								tableName, "MODIFYTIME",
								user.getKnowRegion()));

						times.put("DELETETIME", deleteTime);


						db.deleteRecord(tableName, "ID", ids, times);
						db.insertOrUpdateSync(code, "DELETETIME", deleteTime);
						back.setCount(jsonObj.optInt("total"));
						back.setDeleteTime(deleteTime);
						return back;
					}else{
						back.setCount(-200);
						return back;
					}

				} catch (JSONException e) {
					back.setCount(-200);
					return back;
				}

			}else{
				back.setCount(-1);
				return back;
			}



		}else{
			Log.d("rafe error500",String.valueOf(data.getData()));
			back.setCount(-500);
			return back;
		}
	}

	public int sum(String tableName,int start,String time,String code,String opt){
		time = time.replaceAll(" ", "%20");
		HttpUtilsEx HttpUtilsEx = new HttpUtilsEx();
		String url = new ConfigUtil(context.getResources()).getPreHttpUrl()
				+ context.getString(R.string.update_beijiandanweiInfo)
				+ opt+"/region_code/" + code + "/time/"
				+ time + "/limit/20/offset/"+start+"/username/" + user.getUsername()
				+ "/from/1";
		Log.d("syncdata_url",url);
		HttpBack data= HttpUtilsEx.sendRequest2(url,null, "GET", "UTF-8", authUserName,
				authPassword, user);
		if(data.getCode()==200){
			Log.d("syncdata_data",data.getData());
			int rcode= addupdate(tableName,code,data.getData(),opt);

			return rcode;
		}else{
			Log.d("rafe error500",String.valueOf(data.getData()));
			return -500;
		}


	}
	//婵☆偓鎷烽悡锟犳偐閼哥鎷�
	public JSONArray check2(String code){
		HttpUtilsEx HttpUtilsEx = new HttpUtilsEx();
		String url = new ConfigUtil(context.getResources()).getPreHttpUrl()
				+ "rest/user/syncheck/";

		JSONArray params=db.querySyncByParent(code);
		JSONObject param=new JSONObject();
		try {
			param.put("username", user.getUsername());
			param.put("syn_table", params);
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Log.d("rafe_param",param.toString());

		HttpBack data= HttpUtilsEx.sendRequest4(url,param.toString());
		if(data.getCode()==200){
			Log.d("rafe ok",String.valueOf(data.getData()));
			JSONObject back=null;
			try {
				back = new JSONObject(data.getData());
			} catch (JSONException e) {
				return new JSONArray();
			}
			if(back.optJSONArray("result")!=null){
				return back.optJSONArray("result");
			}


		}else{
			Log.d("rafe error500",String.valueOf(data.getData()));

		}
		return new JSONArray();

	}

	//婵☆偓鎷烽悡锟犲礂閺堢數閾傞柡鍥х摠閺屽﹤螣閳ヨ櫕鍋ラ柣妯垮煐閿燂拷
	public JSONArray check3(String code){
		HttpUtilsEx HttpUtilsEx = new HttpUtilsEx();
		String url = new ConfigUtil(context.getResources()).getPreHttpUrl()
				+ "rest/user/synchecknew/";

		JSONArray params=db.querySyncOther(code);
		JSONObject param=new JSONObject();
		try {
			param.put("username", user.getUsername());
			param.put("syn_table", params);
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Log.d("rafe_param",param.toString());

		HttpBack data= HttpUtilsEx.sendRequest4(url,param.toString());
		if(data.getCode()==200){
			Log.d("rafe ok",String.valueOf(data.getData()));
			JSONObject back=null;
			try {
				back = new JSONObject(data.getData());
			} catch (JSONException e) {
				return new JSONArray();
			}
			if(back.optJSONArray("result")!=null&&back.optInt("status")>0){
				return back.optJSONArray("result");
			} else{
				return null;
			}


		}else{
			Log.d("rafe error500",String.valueOf(data.getData()));

		}
		return null;
	}
	//婵☆偓鎷烽悡锟犳偐閼哥鎷�
	public boolean checkBack(String code){
		HttpUtilsEx HttpUtilsEx = new HttpUtilsEx();
		String url = new ConfigUtil(context.getResources()).getPreHttpUrl()
				+ "rest/user/synupdate/";

		JSONArray params=db.querySyncByParent(code);
		JSONObject param=new JSONObject();
		try {
			param.put("username", user.getUsername());
			param.put("syn_table", params);
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		HttpBack data= HttpUtilsEx.sendRequest4(url,param.toString());
		if(data.getCode()==200){
			Log.d("rafe ok",String.valueOf(data.getData()));
		}else{
			Log.d("rafe error500",String.valueOf(data.getData()));
		}
		return true;

	}


	public boolean check(String time,String code){
		HttpUtilsEx HttpUtilsEx = new HttpUtilsEx();
		String url = new ConfigUtil(context.getResources()).getPreHttpUrl()
				+ context.getString(R.string.update_beijiandanweiInfo)
				+ "add/region_code/" + code + "/time/"
				+ time + "/limit/1/username/" + user.getUsername()
				+ "/from/1";
		Log.d("rafe  check",url);
		HttpBack data= HttpUtilsEx.sendRequest2(url,null, "GET", "UTF-8", authUserName,
				authPassword, user);
		if(data.getCode()==200){
			try {
				JSONObject jsonObj=  new JSONObject(data.getData());
				return jsonObj.optInt("total")>0;
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				return false;
			}
		}else{
			Log.d("rafe error500",String.valueOf(data.getData()));
			return false;
		}


	}


	private int addupdate(String tablename,String code,String responseBody,String type){



		JSONObject jsonObj=null;
		try {
			jsonObj = new JSONObject(responseBody);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -500;
		}
		String status = jsonObj.optString("status");
		Log.d("rafe", jsonObj.optString("total","0"));
		if (CommonConstants.serverIsOk(status)&&jsonObj.optInt("total",-1)>0) {
			addupdate_ent(jsonObj,code,type);
			return jsonObj.optInt("total",-1);
		}else{

			return -500;
		}
	}
	public boolean isEmpty(String tablename){
		return db.isEmpty(tablename);
	}
	private void addupdate_ent(JSONObject jsonObj,String docode,String type){


		JSONArray jsonArray = jsonObj
				.optJSONArray("result");
		List<BeiJianDanWei> beiJianDanWeis = new ArrayList<BeiJianDanWei>();

		String table="";
		if(docode.length()<8){

			return;
		}else{
			table=docode.substring(0, 8);

		}

		String addTime = jsonObj.optJSONObject("modified").optString("datetime");

		for (int i = 0; i < jsonArray.length(); i++) {

			JSONObject bjdwJsonObj = jsonArray
					.optJSONObject(i);

			if (!bjdwJsonObj.isNull("name")) {

				String id = bjdwJsonObj.optString("id");

				String name = bjdwJsonObj
						.optString("name");

				String code = bjdwJsonObj
						.optLong("region_code") + "";

				Integer kind = bjdwJsonObj
						.optInt("kind");

				Double longitude = bjdwJsonObj
						.isNull("longitude") ? null
						: bjdwJsonObj
						.optDouble("longitude");

				Double latitude = bjdwJsonObj
						.isNull("latitude") ? null
						: bjdwJsonObj
						.optDouble("latitude");

				String category = null;

				if (!bjdwJsonObj.isNull("category")) {
					category = bjdwJsonObj
							.optString("category");
				}

				String tel = bjdwJsonObj
						.optString("tel");

				String mobile = null;

				if (!bjdwJsonObj.isNull("mobile")) {
					mobile = bjdwJsonObj
							.optString("mobile");
				}

				String address = bjdwJsonObj
						.optString("address");

				String charge = bjdwJsonObj
						.optString("charge");

				BeiJianDanWei beiJianDanWei = new BeiJianDanWei(
						id, name, code, addTime, null,
						null, address, kind, longitude,
						latitude, category, charge,
						tel, mobile);
				beiJianDanWeis.add(beiJianDanWei);
			}
		}
		db.insertOrUpdateBeiJianDanWei(beiJianDanWeis,table);
		if(type.equals("add")){

			db.insertOrUpdateSync(docode, "ADDTIME", addTime);
		}else if(type.equals("modify")){
			db.insertOrUpdateSync(docode, "MODIFYTIME", addTime);
		}

	}





	public JSONObject searchEntOnline(String key,int start){

		String url = new ConfigUtil(context.getResources()).getPreHttpUrl()
				+ "/rest/ent/keywordlist"
				+ "/region_code/" +user.getKnowRegion() + "/keyword/"
				+ key + "/limit/20/offset/"+(start*20)+"/username/" + user.getUsername()
				+ "/from/1";
		Log.d("rafe url",url);
		HttpUtilsEx HttpUtilsEx = new HttpUtilsEx();

		HttpBack data= HttpUtilsEx.sendRequest2(url,null, "GET", "UTF-8", authUserName,
				authPassword, user);
		if (data.getCode()!=200||!CharsetUtil.isNotNull(data.getData())) {
			return null;
		}


		JSONObject jsonObj =null;
		try {
			jsonObj = new JSONObject(data.getData());

		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}


		return jsonObj;

	}
}
